package com.vanysoft.business.index.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.vanysoft.business.sys.entity.Menu;
import com.vanysoft.business.sys.entity.UserInfo;
import com.vanysoft.business.sys.service.LinkService;
import com.vanysoft.business.sys.service.MenuService;
import com.vanysoft.business.sys.service.NotifyService;
import com.vanysoft.business.sys.service.UserInfoService;
import com.vanysoft.framework.base.action.BaseController;
import com.vanysoft.framework.config.mvc.SessionUser;
import com.vanysoft.framework.exception.VanySoftBaseException;
import com.vanysoft.framework.kaptcha.KaptchaProperties;
import com.vanysoft.framework.messagesource.MessageCodeConstant;
import com.vanysoft.framework.utils.JSONResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 主控制器
 *
 * @author qi_ma
 */
@Controller
public class IndexController extends BaseController {
    private final Log log = LogFactory.getLog(getClass());
    @Resource
    private KaptchaProperties kaptchaProperties;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private MenuService menuService;
    @Resource
    private LinkService linkService;
    @Resource
    private NotifyService notifyService;
    @Resource
    private DefaultKaptcha kaptcha;

    @RequestMapping("/")
    public String login(Model model) {
        model.addAttribute("codeEnable", kaptchaProperties.getEnable());
        return "login/login";
    }

    /**
     * 登陆操作
     */
    @RequestMapping(value = "/login", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JSONResponse login(String username, String password, String code, HttpSession session) throws VanySoftBaseException {
        if (kaptchaProperties.getEnable() && !Objects.equals(code, session.getAttribute(kaptcha.getConfig().getSessionKey()))) {
            // 验证码错误
            throw new VanySoftBaseException(MessageCodeConstant.LoginConstant.CODE_ERROR);
        }
        String token = userInfoService.doLogin(username, password);
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("token", token);
        return new JSONResponse(dataMap);
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        String token = request.getParameter("token");
        if (StringUtils.isNotEmpty(token)) {
            userInfoService.doLogout(token);
        }
        return "redirect:/";
    }

    @RequestMapping("/undefined")
    public String undefined(HttpServletRequest request) {
        String token = request.getParameter("token");
        if (StringUtils.isNotEmpty(token)) {
            userInfoService.doLogout(token);
        }
        return "redirect:/";
    }

    @RequestMapping("/home")
    public String index(HttpServletRequest request) {
        log.info(request.getLocale());
        return "home";
    }

    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @RequestMapping(value = "index/menus")
    @ResponseBody
    public JSONResponse queryIndexMenuAndUserinfo(@SessionUser UserInfo userInfo) throws VanySoftBaseException {
        List<Menu> menus;
        if (userInfo.isAdmin()) {
            menus = menuService.selectAll(userInfo.getId());
        } else {
            menus = menuService.selectByUserId(userInfo.getId());
        }
        List<Menu> menuList = menus.stream().filter(m -> Objects.equals(m.getIsEnable(), "1") && Objects.equals(m.getIsShow(), "1") && Objects.equals(m.getType(), "1")).collect(Collectors.toList());
        menuList = buildMenuTree(menuList);
        return new JSONResponse(menuList);
    }


    @RequestMapping(value = "index/favorites")
    @ResponseBody
    public JSONResponse favorites(@SessionUser UserInfo userInfo) throws VanySoftBaseException {
        List<Menu> menus;
        if (userInfo.isAdmin()) {
            menus = menuService.selectAll(userInfo.getId());
        } else {
            menus = menuService.selectByUserId(userInfo.getId());
        }
        return new JSONResponse(menus.stream().filter(m -> Objects.equals(m.getIsEnable(), "1") && Objects.equals(m.getIsShow(), "1") && Objects.equals(m.getType(), "1") && Objects.equals(m.getIsFavorite(), Boolean.TRUE)).collect(Collectors.toList()));
    }

    @RequestMapping(value = "index/links")
    @ResponseBody
    public JSONResponse links() throws VanySoftBaseException {
        return new JSONResponse(linkService.selectAll().stream().filter(l -> "1".equals(l.getIsEnable())).collect(Collectors.toList()));
    }

    @RequestMapping(value = "index/notifies")
    @ResponseBody
    public JSONResponse notifies() throws VanySoftBaseException {
        Map<String, Object> condition = new HashMap<>();
        condition.put("isEnable", "1");
        condition.put("expiryDateEnd", LocalDate.now());
        return new JSONResponse(notifyService.selectAll(condition));
    }

    @RequestMapping(value = "index/userInfo")
    @ResponseBody
    public JSONResponse userInfo(@SessionUser UserInfo userInfo) throws VanySoftBaseException {
        return new JSONResponse(userInfo);
    }

    @RequestMapping(value = "index/favoriteMenu")
    @ResponseBody
    public JSONResponse doFavorite(@SessionUser UserInfo userInfo, String menuId, Boolean isFavorite) throws VanySoftBaseException {
        boolean flag = userInfoService.saveFavorite(userInfo.getId(), menuId, isFavorite);
        return new JSONResponse(flag ? MessageCodeConstant.RTN_CODE_SUCCESS : MessageCodeConstant.RTN_CODE_UPDATE_FAIL);
    }
}
